<?php



/**
 * This is the model class for table "blog_post".
 *
 * The followings are the available columns in table 'blog_post':
 * @property string  $id
 * @property string  $title
 * @property string  $alias
 * @property string  $info
 * @property string  $content
 * @property string  $image
 * @property string  $status
 * @property string  $create_date
 * @property integer $update_date
 * @property string  $publish_date
 * @property string  $ordering
 * @property string  $lang
 * @property integer $user_id
 * @property integer $owner_id
 * @property string  $tags
 * @property integer $priority
 * @property string  $page
 */
class Post extends CActiveRecord {
    private $_oldTags;

    /**
     * Returns the static model of the specified AR class.
     *
     * @param string $className active record class name.
     *
     * @return Post the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'blog_post';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, tags', 'required'),
            array('update_date, user_id, owner_id, priority, ordering', 'numerical', 'integerOnly' => true),
            array('title, alias, image, tags', 'length', 'max' => 255),
            array('status, page, lang', 'length', 'max' => 1),
            array('info, content, create_date, publish_date', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array(
                'id, title, alias, info, content, image, status, create_date, update_date, publish_date, ordering, lang, user_id, owner_id, tags, priority, page',
                'safe',
                'on' => 'search'
            ),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'comments'           => array(
                self::HAS_MANY,
                'Comment',
                'post_id',
                'condition' => 'comments.status=' . APPROVED . ' and comments.is_spam=' . NONE_SPAM
            ),
            'countComment'       => array(
                self::STAT,
                'Comment',
                'post_id',
                'condition' => 'status=' . APPROVED,
            ),
            'countCommentUnRead' => array(
                self::STAT,
                'Comment',
                'post_id',
                'condition' => 'status=' . PENDING,
            ),
//            'cate' => array(self::BELONGS_TO, 'Category', 'cate_id'),
            'user'               => array(self::BELONGS_TO, 'User', 'user_id'),
            'owner'              => array(self::BELONGS_TO, 'User', 'owner_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id'           => 'ID',
            'title'        => 'Title',
            'alias'        => 'Alias',
            'info'         => 'Info',
            'content'      => 'Content',
            'image'        => 'Image',
            'status'       => 'Status',
            'create_date'  => 'Create Date',
            'update_date'  => 'Update Date',
            'publish_date' => 'Publish Date',
            'ordering'     => 'Ordering',
            'lang'         => 'Lang',
            'user_id'      => 'User',
            'owner_id'     => 'Owner',
            'tags'         => 'Tags',
            'priority'     => 'Priority',
            'page'         => 'Page',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.
        $criteria = new CDbCriteria;
        $criteria->compare('id', $this->id, true);
        $criteria->compare('title', $this->title, true);
        $criteria->compare('alias', $this->alias, true);
        $criteria->compare('info', $this->info, true);
        $criteria->compare('content', $this->content, true);
        $criteria->compare('image', $this->image, true);
        $criteria->compare('status', $this->status, true);
        $criteria->compare('create_date', $this->create_date, true);
        $criteria->compare('update_date', $this->update_date);
        $criteria->compare('publish_date', $this->publish_date, true);
        $criteria->compare('ordering', $this->ordering, true);
        $criteria->compare('lang', $this->lang, true);
        $criteria->compare('user_id', $this->user_id);
        $criteria->compare('owner_id', $this->owner_id);
        $criteria->compare('tags', $this->tags, true);
        $criteria->compare('priority', $this->priority);
        $criteria->compare('page', $this->page, true);

        $criteria->order = 'id ASC';

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => false
        ));
    }

    public static function criteriaModel($lang, $alias, $tag, $date, $limit, $title, $username, $olderId, $priority, $isOnIndex, $orderBy) {
        $criteriaPost = new CDbCriteria();
        $language     = $lang == 'en' ? 2 : 1;
        $criteriaPost->compare('lang', $language);
        $criteriaPost->compare('t.status', APPROVED);
        $userId = Helper::user()->id ? Helper::user()->id : (Yii::app()->controller->id == 'site' ? 1 : '');
        if ($userId) {
            if (!Helper::user()->checkAccess('Super') && !Helper::user()->checkAccess('Administrators')) {
                $criteriaPost->compare('owner_id', $userId);
            }
        }
        if (is_array($limit) && $limit) {
            $criteriaPost->limit  = $limit['end'];
            $criteriaPost->offset = $limit['begin'];
        } elseif (intval($limit)) {
            $criteriaPost->limit = $limit;
        }
        if ($alias) {
            $criteriaPost->compare('alias', $alias);
        }
        if ($date) {
            $criteriaPost->compare('create_date', $date);
        }
        if ($tag) {
            $criteriaPost->addSearchCondition('tags', $tag);
        }
        if ($title) {
            $criteriaPost->addSearchCondition('title', $title);
        }
        if ($username) {
            $modelUser = CreateCache::usingCache('User', false, $username, $language, 'ordering', '', '', '', $username);
            if (!$modelUser) {
                throw new CHttpException(400, Helper::t('Error_Link'));
            }
            $criteriaPost->compare('owner_id', $modelUser->id);
        }
        if ($olderId) {
            $criteriaPost->compare('id', '<' . $olderId);
        }
        if ($priority) {
            $criteriaPost->compare('priority', $priority);
        }
        if ($isOnIndex) {
            $criteriaPost->compare('page', $isOnIndex);
        }
        $criteriaPost->order = $orderBy;

        return $criteriaPost;
    }

    protected function beforeSave() {
        if ($this->isNewRecord) {
            $this->ordering = Post::model()->count() + 1;
            $this->status   = APPROVED;
            $this->user_id  = $this->owner_id = Helper::user()->id;
            $this->create_date  = date('Y-m-d', time());
        } else {
            $this->create_date = date('Y-m-d', Helper::changeDateToFormat($this->create_date, 'm-d-Y'));
        }
        $requestPost        = Helper::post('Post');
        $this->alias        = Helper::unicode_convert($this->title);
        $this->publish_date = date('Y-m-d', Helper::changeDateToFormat($requestPost['publish_date'], 'm-d-Y'));
        $this->update_date  = time();

        return parent::beforeSave();
    }

    protected function afterFind() {
        $this->publish_date = date('m-d-Y', Helper::changeDateToFormat($this->publish_date));
        $this->create_date  = date('m-d-Y', Helper::changeDateToFormat($this->create_date));
        $this->_oldTags     = $this->tags;

        return parent::afterFind();
    }

    protected function afterSave() {
        Tags::model()->updateFrequency($this->_oldTags, $this->tags);

        return parent::afterSave();
    }

    protected function beforeDelete() {
        $model = $this->model()->getTableSchema()->name;
        $params = array(
            'folder' => Helper::basePath().'/../uploads/'. $model,
            'id' => $this->id,
            'model' => ucfirst($model),
            'imageName' => ''
        );
        Helper::deleteImage($params);

        return parent::beforeDelete();
    }

    protected function afterDelete() {
        Comment::model()->deleteAll('post_id=' . $this->id);
        Tags::model()->updateFrequency($this->tags, '');

        return parent::afterDelete();
    }

    public function getTagLinks() {
        $links = array();
        if (count($this->tags)) {
            foreach (Tags::string2array($this->tags) as $tag)
                $links[] = CHtml::link(CHtml::encode($tag), array('/Blog/post/index', 'tag' => $tag));
        }

        return $links;
    }

    /**
     * Normalizes the user-entered tags.

     */
    public function normalizeTags($attribute, $params) {
        $this->tags = Tags::array2string(array_unique(Tags::string2array($this->tags)));
    }

    public function sortPost() {
        $i = 1;
        if ($_POST['post']) {
            foreach ($_POST['post'] as $id) {
                Post::model()->updateByPk($id, array('ordering' => $i));
                $i++;
            }
        }
    }

    protected function beforeValidate() {
        $postPost = Helper::post('Post');
        if (isset($postPost['page']) && is_array($postPost['page']) && count($postPost['page'] > 1)) {
            $this->page = implode(',', $postPost['page']);
        }

        return parent::beforeValidate();
    }
}